package jt.classic.app.dms.fileupload;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jt.classic.app.dms.DmsManager;
import jt.classic.app.dms.FileVersionUtils;
import jt.classic.system.ISystem;
import jt.classic.system.ISystemException;
import jt.classic.system.SimpleAction;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.database.SystemDataSourceException;
import jt.classic.system.object.IObject;
import jt.classic.system.object.ObjectLCManager;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.user.IUser;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.limp.basework.Table;
import org.limp.basework.console.XSystemConfig;
import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.mine.annex.AnnexException;
import org.limp.mine.annex.AnnexItem;
import org.limp.mine.annex.AnnexItemImpl;
import org.limp.mine.annex.AttFileItem;
import org.limp.mine.annex.AttFileItemImpl;
import org.limp.mine.annex.transactor.AnnexTransactor;
import org.limp.mine.annex.transactor.AnnexTransactorException;


/**
 * 文件在线编辑action
 * @author lvt
 *
 */
public class OnLineEditAction extends SimpleAction {
    /**
     * 保存文件并生成历史记录
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */
    public void save(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        IUser user = ISystem.getSessionUser(request);
        SystemDataSource ds = SystemDataSource.getInstance();
        String filename = null;
        String currentfolderid = null;
        String objid = null;
        String fk_annex_id = null;

        try {
            conn = ds.getConnection();
        } catch (SystemDataSourceException e1) {
            e1.printStackTrace();
        }

        ObjectManager om = new ObjectManager(conn);

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(10240000);

        File tempfile = new File(System.getProperty("java.io.tmpdir"));

        factory.setRepository(tempfile);

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setSizeMax(10002400000L);
        upload.setHeaderEncoding("UTF-8");

        try {
            List items = upload.parseRequest(request);
            FileItem item = null;

            for (int i = 0; i < items.size(); ++i) {
                item = (FileItem) items.get(i);

                if (item.isFormField()) {
                    String fieldName = item.getFieldName();

                    if (fieldName.equals("currentfolderid")) {
                        currentfolderid = item.getString();
                    }

                    if (fieldName.equals("objid")) {
                        objid = item.getString();
                    }

                    if (fieldName.equals("fk_annex_id")) {
                        fk_annex_id = item.getString();
                    }

                    if (fieldName.equals("filename")) {
                        filename = item.getString();
                    }
                }
            }

            for (int i = 0; i < items.size(); ++i) {
                item = (FileItem) items.get(i);

                if ((!(item.isFormField())) && (item.getName().length() > 0)) {
                    addRecord(objid, item, conn, om, user, currentfolderid);
                }
            }

            response.getWriter().print("succeed");
            response.getWriter().flush();
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.getWriter().close();
            SystemDataSource.closeConnection(conn);
        }
    }

    /**
     * 向历史记录表中添加记录
     * @param objid
     * @param item
     * @param conn
     * @param om
     * @param user
     * @param currentfolderid
     */
    public Map addRecord(String objid, FileItem item, Connection conn,
        ObjectManager om, IUser user, String currentfolderid) {
        /* 初始化CommonBean4HSQ （生成一个空实例，手工初始化数据内容） */
        CommonBean4HSQ cbh;
        String id = null;
        Map result = null;
        String fileName = null;
        String lastVersion = null;
        String ladtFileSize = null;
        String newFileSize = (item.getSize() / 1024) + "";
        IObject obj_t;

        //文件信息表的id
        String fk_annx_id_file = null;

        //历史记录表的id
        String fk_annx_id_his = null;
        DmsManager dm = new DmsManager(conn);

        try {
            ObjectLCManager olc = new ObjectLCManager(conn);

            obj_t = olc.getObjectById(objid);

            Table table_t = obj_t.iobject().itable("DOC_BVFABRYJMQ");
            Map result_t = ((Map) ((List) obj_t.icontent(table_t)).get(0));
            fileName = (String) result_t.get("COL_FILENAME");
            lastVersion = (String) result_t.get("COL_VERSION");
            ladtFileSize = (String) result_t.get("COL_FILESIZE");
            fk_annx_id_file = (String) result_t.get("PK_DOC_BVFABRYJMQ");
        } catch (ISystemException e4) {
            e4.printStackTrace();
        }

        FileVersionUtils fileVersionUtils = new FileVersionUtils();
        String newVersion = fileVersionUtils.updateVersion("update", lastVersion);

        try {
            cbh = new CommonBean4HSQ(null);

            String originalFilename = item.getName();
            originalFilename.lastIndexOf("\\");
            /* 设置对象名称 */
            cbh.getResource().put("COL_H_FILENAME", fileName);
            /* 设置其它内容 */
            cbh.getResource().put("COL_H_FILEID", fk_annx_id_file);
            cbh.getResource().put("COL_H_DIRECTORYID", currentfolderid);
            cbh.getResource().put("COL_H_FILESIZE", "" + ladtFileSize);
            cbh.getResource().put("COL_H_STATE", "00");
            cbh.getResource().put("COL_H_VERSION", lastVersion);

            int idx = originalFilename.lastIndexOf('.');
            String fileType = originalFilename.substring(idx + 1,
                    originalFilename.length());
            cbh.getResource().put("COL_H_FILETYPE", fileType);
            cbh.getResource().put("okey", "FILEHISTORY");
            cbh.getResource().put("oname", fileName);
            cbh.getResource().put("ocreatorid", user.id());
            cbh.getResource().put("ocreatorname", user.iname());
            cbh.getResource().put("ounitid", user.igroup().id());
            cbh.getResource().put("ounitname", user.igroup().iname());
            cbh.getResource().put("ounitnumber", user.igroup().inumber());

            /* 设置文件实体内容 */
            // cbh.getResource().put(AnnexItem.ANNEX, annexItem);
            IObject obj = om.auto("FILEHISTORY", cbh);

            Table table = obj.iobject().itable("DOC_FILEHISTORY");
            result = ((Map) ((List) obj.icontent(table)).get(0));
            fk_annx_id_his = (String) result.get("PK_DOC_FILEHISTORY");
            dm.insertEvent(fk_annx_id_file, user.id(), user.iname(), "编辑文件",
                "FILEINFO", lastVersion);
        } catch (ISystemException e2) {
            e2.printStackTrace();
        } catch (AnnexException e3) {
            e3.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // ---------------------------------
        /* 获取上传文件 */
        AttFileItem afitem = new AttFileItemImpl(item, "utf-8");

        /* 上传文件Map */
        Map annexInfo = new HashMap();
        annexInfo.put("file", afitem); // 其中fieldName为文件表单数据实体对应的formname。
                                       /* 待处理附件实例 */

        AnnexItem annexitem = new AnnexItemImpl(annexInfo);
        /* 设置附件关联表主键值 */
        annexitem.setObjectId((String) result.get("PK_DOC_FILEHISTORY"));
        /* 设置附件关联表名称 */
        annexitem.setObjectName("DOC_FILEHISTORY");

        /* 获取附件处理器 */
        String transactor = (String) XSystemConfig.config()
                                                  .getProperty(XSystemConfig.XSYSTEM_ANNEX_TRANSACTOR);
        AnnexTransactor trans;

        try {
            trans = (AnnexTransactor) Class.forName(transactor).newInstance();
            trans.needHelp(conn);

            String FREEHOME = (String) XSystemConfig.config()
                                                    .getProperty(XSystemConfig.XSYSTEM_ANNEX_FREEHOME);
            String RESTRICTHOME = (String) XSystemConfig.config()
                                                        .getProperty(XSystemConfig.XSYSTEM_ANNEX_RESTRICTHOME);
            String REALPATH = (String) XSystemConfig.config()
                                                    .getProperty(XSystemConfig.XSYSTEM_REALPATH);

            trans.setHome(REALPATH, RESTRICTHOME, FREEHOME);
            /* 保存附件 */
            trans.setFreeHome(true);
            trans.save(annexitem);

            //调换fk_annex_id与annex_object并更新版本号
            swift(fk_annx_id_file, fk_annx_id_his, newVersion, newFileSize, conn);

            conn.commit();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (AnnexTransactorException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

            e.printStackTrace();
        }

        return result;
    }

    /**
     * 将附件表中某一文件对应的当前记录与历史记录的fk_annex_id与annex_object
     * @param fk_annx_id_file 文件信息表的id
     * @param fk_annx_id_his 历史记录表的id
     */
    private void swift(String fk_annx_id_file, String fk_annx_id_his,
        String version, String newFileSize, Connection conn) {
        DmsManager dm = new DmsManager(conn);
        dm.swift(fk_annx_id_file, fk_annx_id_his);
        dm.updateVersion(fk_annx_id_file, version, newFileSize);
    }
}
